export function pageViewPlugin() {
  return (md: any) => {
    // 在渲染时处理一级标题
    const defaultRender = md.renderer.rules.heading_open || function(tokens: any, idx: number, options: any, env: any, self: any) {
      return self.renderToken(tokens, idx, options)
    }

    // 处理标题关闭标签
    const defaultHeadingCloseRender = md.renderer.rules.heading_close || function(tokens: any, idx: number, options: any, env: any, self: any) {
      return self.renderToken(tokens, idx, options)
    }

    // 计算字数的函数
    const calculateWordCount = (text: string) => {
      // 移除HTML标签
      const plainText = text.replace(/<[^>]*>/g, '')
      
      // 移除markdown语法（保留表格单元格文本）
      const cleanText = plainText
        .replace(/#{1,6}\s+/g, '') // 移除标题标记
        .replace(/\*\*(.*?)\*\*/g, '$1') // 移除粗体
        .replace(/\*(.*?)\*/g, '$1') // 移除斜体
        .replace(/`(.*?)`/g, '$1') // 移除行内代码
        .replace(/```[\s\S]*?```/g, '') // 移除代码块
        .replace(/\[([^\]]*)\]\([^)]*\)/g, '$1') // 移除链接，保留链接文本
        .replace(/!\[([^\]]*)\]\([^)]*\)/g, '') // 移除图片
        .replace(/^\s*[-*+]\s+/gm, '') // 移除列表标记
        .replace(/^\s*\d+\.\s+/gm, '') // 移除有序列表标记
        .replace(/^\s*>\s+/gm, '') // 移除引用标记
        // 表格：去掉对齐分隔线，保留单元格文本
        .replace(/^\s*\|?(?:\s*:?-{3,}:?\s*\|)+\s*$/gm, '') // 移除对齐分隔线
        .replace(/^\s*\|/gm, '') // 去掉行首竖线
        .replace(/\|/g, ' ') // 其余竖线替换为空格
        .replace(/^\s*---\s*$/gm, '') // 移除分隔线
        .replace(/^\s*`{3,}.*$/gm, '') // 移除代码块标记
        .replace(/^\s*`.*$/gm, '') // 移除行内代码标记
        .replace(/\n\s*\n/g, '\n') // 合并多个空行
        .trim()

      // 中文
      const chineseChars = (cleanText.match(/[\u4e00-\u9fa5\u3000-\u303f\uff00-\uffef]/g) || []).length
      
      // 英文
      const englishChars = (cleanText.match(/[a-zA-Z]/g) || []).length
      
      // 数字
      const digits = (cleanText.match(/[0-9]/g) || []).length
      
      // 总字符数
      const totalChars = chineseChars + englishChars + digits
      
      // 格式化
      if (totalChars >= 1000) {
        return `${(totalChars / 1000).toFixed(1)}K`
      } else {
        return `${totalChars}`
      }
    }

    md.renderer.rules.heading_open = function (tokens: any, idx: number, options: any, env: any, self: any) {
      const token = tokens[idx]
      
      if (token.tag === 'h1') {
        token.meta = token.meta || {}
        token.meta.isH1 = true
      }
      
      return defaultRender(tokens, idx, options, env, self)
    }

    md.renderer.rules.heading_close = function (tokens: any, idx: number, options: any, env: any, self: any) {
      const token = tokens[idx]
      
      // 检查是否是h1标题的关闭标签
      if (token.tag === 'h1') {
        // 获取frontmatter中的自定义参数
        const frontmatter = env.frontmatter || {}
        const customParams = frontmatter.customParams || {}
        
        // 构建自定义内容
        let customContent = ''

         // 发表时间
         if (customParams.uploadTime) {
            customContent += `
              <div class="custom-badge upload-time" style="display: inline-flex; align-items: center; gap: 4px; margin: 0 12px 0 0; padding: 4px 8px; background: #f8f9fa; color: #6c757d; border-radius: 6px; font-size: 12px; border: 1px solid #e9ecef;">
                <span style="font-size: 12px;">📅</span>
                <span>发表于 ${customParams.createTime}</span>
              </div>
            `
          }
        
        // 更新时间
        if (customParams.uploadTime) {
          customContent += `
            <div class="custom-badge upload-time" style="display: inline-flex; align-items: center; gap: 4px; margin: 0 12px 0 0; padding: 4px 8px; background: #f8f9fa; color: #6c757d; border-radius: 6px; font-size: 12px; border: 1px solid #e9ecef;">
              <span style="font-size: 12px;">📅</span>
              <span>更新于 ${customParams.uploadTime}</span>
            </div>
          `
        }
        
        // 作者
        if (customParams.author) {
          customContent += `
            <div class="custom-badge author" style="display: inline-flex; align-items: center; gap: 4px; margin: 0 12px 0 0; padding: 4px 8px; background: #f8f9fa; color: #6c757d; border-radius: 6px; font-size: 12px; border: 1px solid #e9ecef;">
              <span style="font-size: 12px;">👤</span>
              <span>作者: ${customParams.author}</span>
            </div>
          `
        }
        
        // 字数(不用传)
        if (env.source) {
          const wordCount = calculateWordCount(env.source)
          customContent += `
            <div class="custom-badge word-count" style="display: inline-flex; align-items: center; gap: 4px; margin: 12px 0 0 0; padding: 4px 8px; background: #f8f9fa; color: #6c757d; border-radius: 6px; font-size: 12px; border: 1px solid #e9ecef;">
              <span style="font-size: 12px;">📄</span>
              <span>字数 ${wordCount}</span>
            </div>
          `
        } else {
          // 如果无法获取内容，显示默认字数
          customContent += `
            <div class="custom-badge word-count" style="display: inline-flex; align-items: center; gap: 4px; margin: 12px 0 0 0; padding: 4px 8px; background: #f8f9fa; color: #6c757d; border-radius: 6px; font-size: 12px; border: 1px solid #e9ecef;">
              <span style="font-size: 12px;">📄</span>
              <span>字数 计算中...</span>
            </div>
          `
        }
        
        // 访问量从统计服务获取
        customContent += `
          <div class="custom-badge views" style="display: inline-flex; align-items: center; gap: 4px; margin: 12px 0 0 0; padding: 4px 8px; background: #f8f9fa; color: #6c757d; border-radius: 6px; font-size: 12px; border: 1px solid #e9ecef;">
            <span style="font-size: 12px;">👁️</span>
            <span>阅读量 <ViewCount /></span>
          </div>
        `
        
        // 自定义徽章，直接使用
        if (customParams.badges) {
          customContent += customParams.badges
        }
        
        // 如果有内容，包装在容器中并添加在标题关闭标签之后
        if (customContent) {
          customContent = `
            <div class="custom-badges-container" style="margin: 12px 0 20px 0; display: flex; flex-wrap: wrap; align-items: center; gap: 8px;">
              ${customContent}
            </div>
          `
          return defaultHeadingCloseRender(tokens, idx, options, env, self) + customContent
        }
      }
      
      return defaultHeadingCloseRender(tokens, idx, options, env, self)
    }
  }
} 